package com.example.menu;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Random;
import java.util.TimerTask;
import com.example.menu.R;
//import com.example.menu.MainActivity.Timer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
//import android.view.Display;
//import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
//import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

public class Game extends Activity {

	/*
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game);
	}
	
	*/

	// Score variables 
	double score = 0; // This is always increasing, unless a user presses a
						// wrong button, in which case, it goes to 0
	double modifier = 0; // The modifier is what is being added to the score
							// each button press. Uses elapsed time and time
							// difference
	File file; // Used for saving local high scores on a phone.
	FileWriter fw;
	BufferedWriter bw;
	PrintWriter pw; // we might only need fw and bw

	// Time variables
	// Maintain a seconds and milliseconds version of start, previous, current
	// and elapsed time
	double startTime_ms;
	double startTime_s;
	double previousTime_ms;
	double previousTime_s;
	double currentTime_ms;
	double currentTime_s;
	double elapsedTime_ms; // The difference between the current time and the
							// start time
	double elapsedTime_s;
	double timeDiff_ms; // The difference between the current time and the
						// previous time
	double timeDiff_s;
	double timeLeft_ms;
	double timeLeft_s;
	final static int MAX_TIME_S = 30;
	final static int MAX_TIME_MS = MAX_TIME_S * 1000;
	int timer = 30;
	
	// Color variables
	String nextColor_s;
	int nextColor = Color.parseColor("#FF0000"); // This is the integer equivalent of nextColor_s
	int textColor; // This is the color to print the string out in
	int firstButton; 
	// Button resizing variables
	int screenWidth;
	int screenHeight;

	public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";

	Timer myTimer;
	private int mInterval = 1000;
	private Handler mHandler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game);

		//Display display = getWindowManager().getDefaultDisplay();

		//screenWidth = display.getWidth();
		screenHeight = 1; // display.getHeight();
		firstButton = 0; 
		score = 0;
		//update();
		resetTime();
		updateColor();

		mHandler = new Handler();
		startRepeatingTask();
	}

	Runnable mStatusChecker = new Runnable() {
		@Override
		public void run() {
			//updateStatus(); // this function can change value of mInterval
			timer--;
			if (timer == 0) {
				reset();
			}
			else {
				updateTime();
			}
			mHandler.postDelayed(mStatusChecker, mInterval);
		}
	};

	void startRepeatingTask() {
		mStatusChecker.run();
	}

	void stopRepeatingTask() {
		mHandler.removeCallbacks(mStatusChecker);
	}

	public class Timer extends AsyncTask<Void, Void, Void> {
		protected Void doInBackground (Void... args) {	
			updateTime();
			
			if (timeLeft_s <= 0) reset();
			
			return null;
		}

		public void schedule(TimerTask timerTask, int i) {
			// TODO Auto-generated method stub
			
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/******************************************************************************/
	/* START COLOR STUFF */
	/******************************************************************************/
	public void displayColor() {

	}

	public void updateColor() {
		Random r = new Random();
		switch (r.nextInt(4)) {
		case 0:
			nextColor_s = "Red";
			nextColor = Color.parseColor("#FF0000");
			break;
		case 1:
			nextColor_s = "Blue";
			nextColor = Color.parseColor("#0000FF");
			break;
		case 2:
			nextColor_s = "Yellow";
			nextColor = Color.parseColor("#FFFF00");
			break;
		case 3:
			nextColor_s = "Green";
			nextColor = Color.parseColor("#00FF00");
			break;
		}

		switch (r.nextInt(4)) {
		case 0:
			textColor = Color.RED;
			break;
		case 1:
			textColor = Color.BLUE;
			break;
		case 2:
			textColor = Color.YELLOW;
			break;
		case 3:
			textColor = Color.GREEN;
			break;
		}
		TextView colorView = (TextView) findViewById(R.id.textViewColor);
		colorView.setTextColor(textColor);
		colorView.setText(nextColor_s);
	}

	/******************************************************************************/
	/* END COLOR STUFF */
	/******************************************************************************/

	/******************************************************************************/
	/* START TIME STUFF */
	/******************************************************************************/
	public void resetTime() {
		startTime_ms = (double) System.currentTimeMillis();
		startTime_s = startTime_ms / 1000;

		previousTime_ms = startTime_ms;
		previousTime_s = startTime_s;

		currentTime_ms = startTime_ms;
		currentTime_s = startTime_s;

		elapsedTime_ms = 0;
		elapsedTime_s = 0;

		timeDiff_ms = 0;
		timeDiff_s = 0;
	}

	public void displayTime() {
		//TextView timeView = (TextView) findViewById(R.id.textViewTime);
		//timeView.setText("Time: " + String.format("%d", nextColor));
		//String.format("%.2f", elapsedTime_s);
	}

	public void updateTime() {
		previousTime_ms = currentTime_ms;
		previousTime_s = currentTime_s;

		currentTime_ms = (double) System.currentTimeMillis();
		currentTime_s = currentTime_ms / 1000;

		elapsedTime_ms = currentTime_ms - startTime_ms;
		elapsedTime_s = elapsedTime_ms / 1000;

		timeDiff_ms = currentTime_ms - previousTime_ms;
		timeDiff_s = timeDiff_ms / 1000; 
		
		timeLeft_ms = MAX_TIME_MS - elapsedTime_ms;
		timeLeft_s = MAX_TIME_S - elapsedTime_s;
		
		TextView timeView = (TextView) findViewById(R.id.textViewTime);
//		timeView.setText("Time: " + String.format("%.0f", elapsedTime_s));
		timeView.setText("Time: " + String.format("%.0f", timeLeft_s));		
	}

	/******************************************************************************/
	/* END TIME STUFF */
	/******************************************************************************/

	public void setButtons(View view) {

	}

	/******************************************************************************/
	/* START SCORE STUFF */
	/******************************************************************************/
	public void displayScore() {
		TextView scoreView = (TextView) findViewById(R.id.textViewScore);
		scoreView.setText("Score: " + String.format("%.0f", score));
		// note1: the sizeView is only for debugging, it will be removed later
		// note2: the color view needs to be set so it spans the entire width
		// TextView sizeView = (TextView) findViewById (R.id.textViewSizes);
		// sizeView.setText("Size is: " + String.format("%d", screenWidth));

	}

	public void updateScore() {
		// Higher time difference means lower modifier, lower time difference
		// means higher modifier
		// In general, modifier will go up, because elapsed time is always going
		// up
		// Divide by 10 so that the score string doesn't skew the rest of the
		// screen
		//modifier = (elapsedTime_ms / timeDiff_ms / 10);
		//score += modifier;
		score += 1; 
	}

	/******************************************************************************/
	/* END SCORE STUFF */
	/******************************************************************************/
	/******************************************************************************/
	/* START BUTTON ACTIONS */
	/******************************************************************************/
	public void update() {
		updateColor();
		updateTime();
		updateScore(); // update score always has to be after update time,
						// because the modifier is based on timestamps

		displayTime();
		displayScore(); 
	}

	public void reset() { // The same as updateAll however, the score
									// is reset to 0, instead of calling
									// updateScore
		updateColor(); 
		updateTime();
		//score = 0;

//		LayoutInflater inflater = getLayoutInflater();

//		View layout = inflater.inflate(R.layout.custom_toast,
//				(ViewGroup) findViewById(R.id.custom_toast_layout_id));

		
		
		// set the image for the toast
		// ImageView image = (ImageView) layout.findViewById(R.id.toastImage);
		// image.setImageResource(R.drawable.ic_launcher);
		
	//	if (firstButton != 0){
		
			
			/* 
			// set the message for the toast
			TextView text = (TextView) layout.findViewById(R.id.toastText);
			text.setText("Game Over!! Play Again"); // prompts the user to play again
			resetTime();
			
			
			// create the toast
			// note: Toast is final, because the timer requires it
			final Toast toast = new Toast(getApplicationContext());
			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			toast.setDuration(Toast.LENGTH_LONG);
			toast.setView(layout);
			toast.show();
	
			// The Toast Timer
			// This will allow us to control how long the toast appears.
			// There are only 2 options for how long a toast appears: LONG and SHORT
			// However by calling toast.cancel() after a certain amount of time,
			// we can create the effect of a different time for toast duration.
			Timer t = new Timer();
			t.schedule(new TimerTask() {
				@Override
				public void run() {
					toast.cancel();
				}
			}, 500); // this is where we set the time for toast
			*/
		
	 
			// This shuts down the activity 
			//this.finish();
			
			
			// start the game over activity 
			
			/*
			Intent intent = new Intent(this, GameOver.class);
		    startActivity(intent); 
		    // finish this activity
			this.finish();
			*/
			
			/*
			String message = score + ""; 
			
			Intent intent = new Intent(Game.this, GameOver.class);
			intent.putExtra("message", message);
			startActivity(intent);
			*/
			
 
			stopRepeatingTask();

			Intent yourIntent = new Intent(Game.this, GameOver.class);
			Bundle b = new Bundle();
			b.putDouble("key", score);
			yourIntent.putExtras(b);
			startActivity(yourIntent);
			
			
			
			this.finish();
			
			
	//	}
		
		score = 0; 
		firstButton = 1; 
		displayColor();
		displayTime();
		displayScore();
	}

	public void buttonAction(View view, int button) {
		if (button != nextColor) {
			reset();
		} else {
			update();
		}
	}

	public void resetButtons(View view) {

		// Get Imagebuttons
		ImageButton button1 = (ImageButton) findViewById(R.id.button1);
		ImageButton button2 = (ImageButton) findViewById(R.id.button2);
		ImageButton button3 = (ImageButton) findViewById(R.id.button3);
		ImageButton button4 = (ImageButton) findViewById(R.id.button4);

		// Get color int from the ImageButtons
		ColorDrawable colorButton1 = (ColorDrawable) button1.getBackground();
		int colorButton1ID = colorButton1.getColor();
		ColorDrawable colorButton2 = (ColorDrawable) button2.getBackground();
		int colorButton2ID = colorButton2.getColor();
		ColorDrawable colorButton3 = (ColorDrawable) button3.getBackground();
		int colorButton3ID = colorButton3.getColor();
		ColorDrawable colorButton4 = (ColorDrawable) button4.getBackground();
		int colorButton4ID = colorButton4.getColor();

		// Set the new colors

		Random r = new Random();
		switch (r.nextInt(6)) {
		case 0: // Swap 1 and 2
			button1.setBackgroundColor(colorButton2ID);
			button2.setBackgroundColor(colorButton1ID);
			break;
		case 1: // Swap 1 and 3
			button1.setBackgroundColor(colorButton3ID);
			button3.setBackgroundColor(colorButton1ID);
			break;
		case 2: // Swap 1 and 4
			button1.setBackgroundColor(colorButton4ID);
			button4.setBackgroundColor(colorButton1ID);
			break;
		case 3: // Swap 2 and 3
			button2.setBackgroundColor(colorButton3ID);
			button3.setBackgroundColor(colorButton2ID);
			break;
		case 4: // Swap 2 and 4
			button2.setBackgroundColor(colorButton4ID);
			button4.setBackgroundColor(colorButton2ID);
			break;

		case 5: // Swap 3 and 4
			button3.setBackgroundColor(colorButton4ID);
			button4.setBackgroundColor(colorButton3ID);
			break;
		}

	}

	public void buttonPress(View view) {
		// Color buttonColor = view.getBackgroundColor();

		ColorDrawable buttonColor = (ColorDrawable) view.getBackground();
		int colorId = buttonColor.getColor();

		// TextView scoreView = (TextView) findViewById(R.id.textViewScore);
		// scoreView.setText("Score: " + String.format("%d", colorId));
		buttonAction(view, colorId);

		resetButtons(view);

	}

	/******************************************************************************/
	/******************************************************************************/
	/* END BUTTON ACTIONS */
	/******************************************************************************/
}
